# -*- coding: utf-8 -*-
import requests

import time

def get_all_Symbol(s=None):
    # 获取所有的货币对
    all = [
        "audcad", "audchf", "audjpy", "audnzd", "audusd",
        "cadchf", "cadjpy",
        "chfjpy",
        "euraud", "eurcad", "eurchf", "eurgbp", "eurjpy", "eurusd",
        "gbpaud", "gbpchf", "gbpjpy", "gbpcad", "gbpnzd", "gbpusd",
        "nzdcad", "nzdchf", "nzdjpy", "nzdusd",
        "usdcad", "usdchf", "usdjpy",
    ]
    if s:
        return [i for i in all if s in i]
    else:
        return all


# 爬取外汇数据
def get_data_from_sina(Symbol = 'eurusd'):
    """此方法是转为爬取来自新浪财经的数据而设计的"""
    cut = 500

    url_harf = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_s" + Symbol + "2020_1_29=/NewForexService.getDayKLine?symbol=fx_s" + Symbol + "&_=2020_1_29"
    url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_fx_seurusd2020_1_29=/NewForexService.getDayKLine?symbol=fx_seurusd&_=2020_1_29"
    # url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20_DINIW2019_09_25=/NewForexService.getDayKLine?symbol=DINIW&_=2019_09_25"
    url = url_harf
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }

    response = requests.get(url=url, headers=headers)

    # 去除杂质
    newString = ''

    for i in response.text:
        if i in '0123456789,.-|':
            newString += i
    newString = '[["' + newString.replace(',', '","').replace('","|', '"],["') + '"]]'
    newString = eval(newString)
    # print(newString)

    return newString[cut * -1:]


if __name__ == '__main__':
    # 开盘    最低    最高    收盘
    a = get_data_from_sina()
    print(a)

    for i in get_all_Symbol():
        if  get_data_from_sina(Symbol = i):
            if len(get_data_from_sina(Symbol = i))>50:
                print("成功获取:"+i)
                time.sleep(2)
            else:
                print("失败获取:" + i)
                time.sleep(5)
            print(get_data_from_sina(Symbol = i))


